<template>
  <div class="ipfs-storage">
    <h2>IPFS 文件存储</h2>
    <div class="input-section">
      <input v-model="fileName" placeholder="输入文件名" class="input-field" />
      <input v-model="ipfsHash" placeholder="输入IPFS Hash" class="input-field" />
      <button @click="uploadFile" class="action-btn">上传文件</button>
    </div>

    <div class="query-section">
      <input v-model="queryFileName" placeholder="输入要查询的文件名" class="input-field" />
      <button @click="getIpfsHash" class="action-btn">查询文件</button>
      <div v-if="storedHash" class="result">
        存储的IPFS Hash: {{ storedHash }}
        <a :href="'https://ipfs.io/ipfs/' + storedHash" target="_blank" class="view-link"
          >查看文件</a
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ethers } from 'ethers';
import { ABIS } from '../contracts/abi';
import { CONTRACT_ADDRESSES } from '../contracts/config';

let provider;
let signer;
let contract;

const fileName = ref('');
const ipfsHash = ref('');
const queryFileName = ref('');
const storedHash = ref('');
const isInitialized = ref(false);

async function initializeContract() {
  try {
    if (window.ethereum) {
      // 请求用户授权连接钱包
      await window.ethereum.request({ method: 'eth_requestAccounts' });
      provider = new ethers.BrowserProvider(window.ethereum);
      // 获取签名者
      signer = await provider.getSigner();
    } else {
      provider = new ethers.JsonRpcProvider('http://127.0.0.1:8545');
      const accounts = await provider.listAccounts();
      if (accounts.length === 0) {
        throw new Error('没有可用的账户');
      }

      signer = accounts[0];
    }

    // 使用hardhat网络的合约地址
    const contractAddress = CONTRACT_ADDRESSES.HARDHAT.IPFS;

    // 初始化合约
    contract = new ethers.Contract(contractAddress, ABIS.IPFS, provider);

    // 检查合约是否存在
    const code = await provider.getCode(contractAddress);
    if (code === '0x') {
      throw new Error('合约在本地网络上不存在');
    }

    // 检查合约方法
    console.log('合约方法:', {
      upload: contract['upload'],
      interface: contract.interface.format()
    });

    isInitialized.value = true;
    console.log('合约初始化成功');
  } catch (error) {
    console.error('初始化合约失败:', error);
    throw error;
  }
}

async function uploadFile() {
  if (!fileName.value || !ipfsHash.value) {
    console.error('请输入文件名和IPFS Hash');
    return;
  }

  if (!isInitialized.value) {
    try {
      await initializeContract();
    } catch (error) {
      console.error('合约初始化失败:', error);
      return;
    }
  }

  if (!contract) {
    console.error('合约未初始化');
    return;
  }

  try {
    console.log('开始上传文件...');
    console.log('参数:', {
      fileName: fileName.value,
      ipfsHash: ipfsHash.value
    });

    // 使用签名者发送交易
    const contractWithSigner = contract.connect(signer);
    const tx = await contractWithSigner.upload(fileName.value, ipfsHash.value);

    console.log('交易已发送，等待确认...');
    console.log('交易hash:', tx.hash);

    const receipt = await tx.wait();
    console.log('交易已确认:', {
      blockNumber: receipt.blockNumber,
      gasUsed: receipt.gasUsed.toString(),
      transactionHash: receipt.transactionHash
    });

    console.log('文件上传成功');

    // 清空输入框
    fileName.value = '';
    ipfsHash.value = '';
  } catch (error) {
    console.error('上传文件失败:', error);
    // 输出更详细的错误信息
    console.error('错误详情:', {
      code: error.code,
      message: error.message,
      data: error.data,
      transaction: error.transaction
    });
  }
}

async function getIpfsHash() {
  if (!queryFileName.value) {
    console.error('请输入要查询的文件名');
    return;
  }

  try {
    const hash = await contract.getIPFSHash(queryFileName.value);
    storedHash.value = hash;
  } catch (error) {
    console.error('获取IPFS Hash失败:', error);
    storedHash.value = '';
  }
}

onMounted(async () => {
  try {
    await initializeContract();
  } catch (error) {
    console.error('初始化失败:', error);
  }
});
</script>

<style scoped>
.ipfs-storage {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.input-section,
.query-section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.input-field {
  width: 100%;
  padding: 8px;
  margin: 8px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.action-btn {
  width: 100%;
  padding: 10px;
  margin: 8px 0;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-btn:hover {
  background-color: #45a049;
}

.result {
  margin-top: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.view-link {
  display: inline-block;
  margin-left: 10px;
  color: #007bff;
  text-decoration: none;
}

.view-link:hover {
  text-decoration: underline;
}
</style>
